﻿// JavaScript Document
var types = ["全部","亲子","实践","讲座","科技","自然","动物","生活","健康","其它"];
var areas = ["全部","卢湾区","黄浦区","静安区","徐汇区","虹口区","长宁区","闸北区","杨浦区","浦东新区","宝山区","嘉定区","松江区","青浦区","南汇区","奉贤区","金山区","崇明县"];
var tickets = ["全部","免费","优惠","全价"];
					//"活动名称","活动类型","活动区域","开始时间","结束时间","门票类型","链接","介绍图片","地址"

var type=null;
	var area=null;
	var days = null;
	var ticketType = null;
	var result = null;
	
	var pageSize = 12;

function filter(type,area,days,ticket){
	var result= new Array();
	//console.log("type:"+type+" area:"+area+" days:"+days.length);
	for(var i=0;i<activityData.length;i++){
		if(matchFilter(activityData[i],type,area,days,ticket))
			result.push(activityData[i]);
	}
	//console.log("result.length:"+result.length);
	return result;
}



function matchFilter(data,type,area,days,ticket){
		if(area!=null && area !=0 && area != data[areaIndex])
			return false;
			
		if(type!=null && type !=0 ){
			var isType = false;
			for(var i=0;i<data[typeIndex].length;i++){
				if(type==data[typeIndex][i]){
					isType = true;
					break;
				}
			}
			if(!isType)
				return false;
		}
		
		if(days!=null && days.length > 0){
			var isOpen = false;
			var aStartTime = Date.parse(data[startTimeIndex]);
			var aEndTime =	Date.parse(data[endTimeIndex]);
			for(var i=0; i<days.length;i++){
				var aday = days[i];
				//console.log("aday:"+aday.getFullYear()+"-"+(aday.getMonth()+1)+"-"+aday.getDate());
				var startTime = new Date(aday.getFullYear(),aday.getMonth(),aday.getDate(),0,0,0).getTime();
				var endTime = new Date(aday.getFullYear(),aday.getMonth(),aday.getDate(),23,59,0).getTime();
				if(startTime>aEndTime|| endTime<aStartTime){
					isOpen = false;
				}
				else{
					isOpen= true;
					break;
				}
				}
				if(!isOpen)
					return false;
			}
		if(ticket!=null && ticket!= 0 &&ticket!=data[ticketIndex])
			return false;
		
		return true;
}



var maxItemNum = 6;

//无限滚动
  $(document).on("pageInit", "#page-infinite-scroll-bottom", function(e, id, page) {
    var loading = false;
    // 每次加载添加多少条目
    var itemsPerLoad = 3;
    // 最多可加载的条目
    
    var lastIndex = 0;
    function addItems(number, lastIndex) {
      var html = buildDomFromData(lastIndex,number);
	  //console.log("build "+ lastIndex+" :"+html);
      // 添加新条目
      $("#listRoot").append(html);
    }
    $(page).on('infinite', function() {
      // 如果正在加载，则退出
      if (loading) return;
      // 设置flag
      loading = true;
      // 模拟1s的加载过程
      setTimeout(function() {
        // 重置加载flag
        loading = false;
		lastIndex = $('.list-container li').length;
		
        if (lastIndex+1 >= result.length) {
          // 加载完毕，则注销无限加载事件，以防不必要的加载
          $.detachInfiniteScroll($('.infinite-scroll'));
          // 删除加载提示符
          $('.infinite-scroll-preloader').remove();
          return;
        }
		//console.log("lastIndex:"+lastIndex+"  ==="+result.length);
        addItems(itemsPerLoad,lastIndex);
        // 更新最后加载的序号
        
        $.refreshScroller();
      }, 1000);
    });
  });
 

function buildDomFromData(startIndex,num){
	var content = "";
	for(var i=startIndex; i<startIndex+num;i++){
			
			var startTimes = result[i][startTimeIndex].split(" ");
			var endTimes = result[i][endTimeIndex].split(" ");
			content +='<li class="item-content"><div class="item-inner"><div class="item-jj"><a href="jjhd_info.html?id='+result[i][numberIndex]+
			'"><img src="../web2/'+result[i][imgIndex]+'" alt=""/><span>'+
			result[i][nameIndex]+'</span><i>'+result[i][addressIndex]+'<br/>日期：'+startTimes[0]+'--'+endTimes[0]+'<br/>开放时间：'
			+startTimes[1]+"--"+endTimes[1]+'</i></a></div> </div> </li>';
			
	}
	return content;
}

function buildDays(obj){
	 var date = new Date(); 
	  var mystate=obj.attr("data-state");
		days = new Array();
		$(".list_3a_data").each(function(){
			var ms = Date.parse($(this).attr("data-data"));
			var cha = date.getTime() - ms;
			 switch(mystate)
			{
			case '1':
			   if (cha < 0 ) {
			   		$(this).hide(0);
				
			   }
			   else{
			   		if($(this).hasClass("sel"))
			   			days.push(new Date(ms));
			   }
			  break;
			case '2':
			  if (cha >= 0) {$(this).hide(0)}
			   else{
			   		if($(this).hasClass("sel"))
			   			days.push(new Date(ms));
			   }
			  break;
			default:
				if($(this).hasClass("sel"))
			   	days.push(new Date(ms));
			   
				break;
			} 
	  		
	  });
	
	
	 	
}

function changeDays(obj){
	
	if(obj.hasClass("sel")){
		  obj.removeClass('sel');
		  var ms = Date.parse(obj.attr("data-data"));
		  var theDay = new Date(ms);
		  
		  for(var i=0;days!=null&& i<days.length;i++){
		  
			if(days[i].getDate()==theDay.getDate() && days[i].getMonth() == theDay.getMonth() && days[i].getFullYear() == theDay.getFullYear()){
				//console.log("pop:"+theDay.getDate());
				days.splice(i,1);
				break;
			}
		  }
	  
      }else{
	  	obj.addClass('sel');
	  	var ms = Date.parse(obj.attr("data-data"));
		if(days == null)
			days = new Array();
	  	days.push(new Date(ms));
	  	
	  
	  }	
	  
	  
}
  
function refreshList2(){
	
	
	if(result == null )
		return;
	var num = result.length>maxItemNum ? maxItemNum : result.length;
	var content = buildDomFromData(0,num);
	
	
	$("#listRoot").html(content);
}

function refreshList(){
		var content = "";
		pageNum =  Math.ceil(result.length/pageSize);
		
		listPageLine(pageNum,pageIndex);
		var num = result.length-pageIndex*pageSize;
		num = num > pageSize ? pageSize : num;
		
		for(var j=0;result!=null && j<num;j++){
			var i = pageIndex*pageSize+j;
			var startTimes = result[i][startTimeIndex].split(" ");
			var endTimes = result[i][endTimeIndex].split(" ");
			content += '<li onmouseover="poppingName(\'nameDiv\','+i+');" onmouseout="stopPop();"><a href="wzhdz_info.html?id='+result[i][numberIndex]+'"><img src="'
			+result[i][imgIndex]+'" alt=""/><i id="nameDiv'+i+'">'
			+result[i][nameIndex]+'</i></a><p>日期：'
			+startTimes[0]+'--'+endTimes[0]+'<br/>开放时间：'
			+startTimes[1]+"--"+endTimes[1]+'<br/>地址：'+result[i][addressIndex]+
			
			'<br/></p></li>';
		}
		
		if(!isButtonFixed){
		 	startPageIndex = 0;
			if(pageIndex>2)
				startPageIndex = pageIndex-2;
		}
		
		
		$("#listRoot").html(content);
	}
	
	
	
	function refreshListByStartTime(){
		
		if(result!=null && result.length > 1){
			pageIndex = 0;
			result = result.sort(sortByStartTimeAes);
			refreshList();
		}
	}
	
	function refreshListByEndTime(){
		
		if(result!=null && result.length > 1){
			pageIndex = 0;
			result = result.sort(sortByEndTimeAes);
			
			refreshList();
		}
	}
	
	function refreshListByClick(){
		var idList = "";
		
		if(result!=null&&result.length > 1){
			
			for(var i=0;i<result.length;i++){
				
				idList+=result[i][numberIndex];
				if(i!=result.length-1){
					idList+=",";
				}
			}
			var obj = $.ajax({url:clickRoot+"/getClicks?itemIds="+idList,async:false});
			
			var clicks = obj.responseText.split(",");
			if(result!=null&&result.length==clicks.length){
				for(var i=0;i<result.length;i++){
					result[i][clickIndex] = clicks[i];
					
				}
				pageIndex = 0;
				result = result.sort(sortByClickDes);
			
				refreshList();
			}
		}
	}
	
	var popName = null;
	var popIndex = 0;
	var popObj = null;
	var minPopLength=15;
	var popDiv = null;
	function poppingName(prefix,i){
		popName = result[i][nameIndex];
		popIndex = 0;
		popDiv = prefix+i;
		if(popName!=null&&popName.length>minPopLength){
			//popName = "                " +popName;
			popping();
		}
	}
	
	function popping(){
		$("#"+popDiv).html(popName.substring(popIndex));
		popIndex++;
		var time = 300;
		if(popIndex == 1){
			time = 1000;
		}
		else if(popIndex>=popName.length-minPopLength){
			popIndex = 0;
			time = 2000;
		}
		
		popObj = setTimeout(popping,time);
		
	}
	
	function stopPop(){
		if(popObj!=null)
			clearTimeout(popObj);
		popObj = null;
		$("#"+popDiv).html(popName);
	}


	


function initData(){
	var url = window.location.href;
	  
   	 id = GetArgsFromHref(url,"id");
	
	
   	for(var i=0;i<activityData.length;i++){
		if(activityData[i][0]==id){
			
			return activityData[i];
			break;
		}
	}	
	
	return null;
}

function findRelated(data){
	var type= data[typeIndex];
	var num = 3;
	var okNum=0;
	var related = new Array();
	var date = new Date();
	var dataTime = date.getTime();
	
	var related2 = new Array();
	for(var i=0;i<activityData.length;i++){
		var endTime = Date.parse(activityData[i][endTimeIndex]);
		
			if(type.length>1 && data[numberIndex]!=activityData[i][numberIndex]&&
				dataTime < endTime && 
				activityData[i][typeIndex].toString() == type.toString()){
				 
					related[okNum] =  activityData[i];
					okNum++;
					if(okNum == num)
						break;
			}
			else if(data[numberIndex]!=activityData[i][numberIndex]&& 
			        dataTime < endTime && 
					isContained((activityData[i][typeIndex]),type)){
				console.log("dataTime:"+dataTime+" endTime:"+endTime);
				related2.push(i);								 
			}
	}
	var num2 = num - okNum;
	
	if(num2 > 0 ){
		if(num2 >= related2.length){
			for(var i=0;i<related2.length;i++){
				related.push(activityData[related2[i]]);		
			}
			
		}
		else{
			
			var okArray = new Array();
			for(var i=0;i<num2;i++){
				var isUsed = true;
				while(isUsed){
					var toUseId = Math.floor(Math.random()*related2.length);
					console.log("toUseId:"+toUseId);
					isUsed = false;
					for(var j=0;j<okArray.length;j++){
						if(toUseId == okArray[j]){
							isUsed = true;
							break;	
						}
					}
					if(!isUsed){
						okArray.push(toUseId);
						related.push(activityData[related2[toUseId]]);
					}
					
				}
			}
		}
		
			
	}
	return related;
}

function isContained(aType,thisType){
	
		
		var types1 = thisType;
		var types2 = aType;
		for(var i=0;i<types2.length;i++){
			for(var j=0;j<types1.length;j++){
				if(types2[i]==types1[j])
					return true;
			}
		}
	
	return false;
}


	

